package com.example.springboot.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot.common.Result;
import com.example.springboot.entity.Check;
import com.example.springboot.entity.DormRoom;
import com.example.springboot.service.CheckService;
import com.example.springboot.service.DormRoomService;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/check")
public class CheckController {

    @Resource
    private CheckService checkService;
    @Resource
    private DormRoomService dormRoomService;

    @PostMapping("/add")
    public Result<?> add(HttpSession session, @RequestBody Check check) {
        String username = ((JSONObject)JSON.toJSON(session.getAttribute("User"))).getString("name");
        check.setOperatorName(username);
        check.setDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        int i = checkService.addNewOrder(check);
        if (i == 1) {
            return Result.success();
        } else {
            return Result.error("-1", "添加失败");
        }
    }

    @GetMapping("/avg")
    public Result<?> getMonthlyAvgScores(
            @RequestParam(required = false) String monthFilter  // 可选参数，格式如 "2025-03"
    ) {
        // 1. 查询所有检查记录
        List<Check> checks = checkService.list();

        // 2. 按月份和宿舍号分组，计算平均分
        Map<String, Map<Integer, Double>> monthlyAvgScores = checks.stream()
                .collect(Collectors.groupingBy(
                        check -> check.getDate().substring(0, 7), // "2025-04"
                        Collectors.groupingBy(
                                Check::getRoomid,
                                Collectors.averagingDouble(Check::getGrade)
                        )));
        // 3. 如果有月份筛选参数，只保留该月份的数据
        if (monthFilter != null && !monthFilter.isEmpty()) {
            monthlyAvgScores = monthlyAvgScores.entrySet().stream()
                    .filter(entry -> entry.getKey().equals(monthFilter))
                    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
        }
        // 4. 先按月份分组，再在每个月份内按avg_score降序排序
        Map<String, List<JSONObject>> groupedByMonth = monthlyAvgScores.entrySet().stream()
                .flatMap(monthEntry ->
                        monthEntry.getValue().entrySet().stream()
                                .map(dormEntry -> {
                                    JSONObject item = new JSONObject();
                                    item.put("month", monthEntry.getKey());
                                    item.put("room_id", dormEntry.getKey());
                                    double avg = dormEntry.getValue();
                                    BigDecimal formattedAvg = new BigDecimal(avg).setScale(2, BigDecimal.ROUND_HALF_UP);
                                    item.put("avg_score", formattedAvg.doubleValue());
                                    return item;
                                })
                )
                .collect(Collectors.groupingBy(
                        item -> item.getString("month"),
                        Collectors.collectingAndThen(
                                Collectors.toList(),
                                list -> list.stream()
                                        .sorted(Comparator.comparingDouble(
                                                (JSONObject o) -> o.getDouble("avg_score")).reversed())
                                        .collect(Collectors.toList())
                        )
                ));
        // 5. 转换为前端需要的格式
        List<JSONObject> finalResult = new ArrayList<>();
        groupedByMonth.forEach((month, dormList) -> {
            JSONObject monthData = new JSONObject();
            monthData.put("dorms", dormList);
            finalResult.add(monthData);
        });

        return Result.success(finalResult);
    }


    @PutMapping("/update")
    public Result<?> update(@RequestBody Check check) {
        int i = checkService.updateNewOrder(check);
        if (i == 1) {
            return Result.success();
        } else {
            return Result.error("-1", "更新失败");
        }
    }

    @GetMapping("/find")
    public Result<?> findPage(HttpSession session, @RequestParam(defaultValue = "1") Integer pageNum,
        @RequestParam(defaultValue = "30") Integer pageSize, @RequestParam(defaultValue = "") String search,
        @RequestParam(defaultValue = "") String date1, @RequestParam(defaultValue = "") String date2) {
        // 如果是学生, 则只能看见自己宿舍的费用
        String username = ((JSONObject)JSON.toJSON(session.getAttribute("User"))).getString("username");
        String identity = (String)JSON.toJSON(session.getAttribute("Identity"));
        Integer dormRoomId = null;
        if (StringUtils.equals("stu",identity)){
            DormRoom dormRoom = dormRoomService.judgeHadBed(username);
            dormRoomId = Optional.ofNullable(dormRoom).orElse(new DormRoom()).getDormRoomId();
        }
        Page page = checkService.find(pageNum, pageSize, search, date1, date2,dormRoomId);
        if (page != null) {
            return Result.success(page);
        } else {
            return Result.error("-1", "查询失败");
        }
    }
    @GetMapping("/finden")
    public Result<?> findPageen(HttpSession session, @RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "30") Integer pageSize, @RequestParam(defaultValue = "") String search,
                              @RequestParam(defaultValue = "") String date1, @RequestParam(defaultValue = "") String date2) {
        // 如果是学生, 则只能看见自己宿舍的费用
        String username = ((JSONObject)JSON.toJSON(session.getAttribute("User"))).getString("username");
        String identity = (String)JSON.toJSON(session.getAttribute("Identity"));
        Integer dormRoomId = null;
        if (StringUtils.equals("stu",identity)){
            DormRoom dormRoom = dormRoomService.judgeHadBed(username);
            dormRoomId = Optional.ofNullable(dormRoom).orElse(new DormRoom()).getDormRoomId();
        }
        Page page = checkService.finden(pageNum, pageSize, search, date1, date2,dormRoomId);
        if (page != null) {
            return Result.success(page);
        } else {
            return Result.error("-1", "查询失败");
        }
    }
    @GetMapping("/find/{name}")
    public Result<?> individualFind(@RequestParam(defaultValue = "1") Integer pageNum,
        @RequestParam(defaultValue = "10") Integer pageSize, @RequestParam(defaultValue = "") String search,
        @PathVariable String name) {
        System.out.println(name);
        Page page = checkService.individualFind(pageNum, pageSize, search, name);
        if (page != null) {
            return Result.success(page);
        } else {
            return Result.error("-1", "查询失败");
        }
    }

    @DeleteMapping("/delete/{id}")
    public Result<?> delete(@PathVariable Integer id) {
        int i = checkService.deleteOrder(id);
        if (i == 1) {
            return Result.success();
        } else {
            return Result.error("-1", "删除失败");
        }
    }


}
